﻿using Iot.Device.Sht3x;

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Device.Gpio;
using System.Device.I2c;
using System.Text;
using System.Threading;
using System.Linq;
using System.IO.Ports;
using IotDeviceToolHepler.Utils;

namespace IotDeviceToolHepler.Device
{
    /// <summary>
    /// RS485工业级光强度传感器B-RS-L30 光照度传感器，外形小巧，工作稳定，采用标准的 Modbus-RTU 通讯协议，适用于各种工业环境使用。
    /// </summary>
    public static class SensorLightBRSL30
    {
        //运行调用例子
        public static void Test()
        {
            while (true)
            {
                string portName = "/dev/ttyS3";
                int baudRate = 9600;
                GetData(portName, baudRate);
            }
        }

        /// <summary>
        /// 香橙派调用 
        /// </summary>
        public static void GetData(string portName, int baudRate)
        {
            //portName树莓派调用/dev/ttyAMA0
            //portName香橙派调用/dev/ttyS3
            SerialPort serial = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
            serial.Open();
            // DataReceived是串口类的一个事件，通过+=运算符订阅事件，如果串口接收到数据就触发事件，调用DataReceive_Method事件处理方法
            serial.DataReceived += new SerialDataReceivedEventHandler(DataReceiveMethod);
            while (true)
            {
                //查光照度指令
                serial.Write(DataTypeChangeHelper.StrToHexByte("01 03 00 02 00 02 65 CB"), 0, 8);
                Thread.Sleep(2000);
            }
        }

        /// <summary>
        /// 接收信息事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DataReceiveMethod(object sender, SerialDataReceivedEventArgs e)
        {
            //sender是事件触发对象，通过它可以获取到mySerialPort
            SerialPort serialport = (SerialPort)sender;
            int len = serialport.BytesToRead;
            byte[] recvdata = new byte[len];
            serialport.Read(recvdata, 0, len);
            var str = DataTypeChangeHelper.byteToHexStr(recvdata);
            if (str.Length > 10)
            {
                string result = str.Substring(6, 8);
                int result16 = DataTypeChangeHelper.To16Convert10(result);
                Console.WriteLine("");
                Console.WriteLine(DateTime.Now + " 光照强度:" + (result16 / 1000.0).ToString() + "lur");
            }
        }

    }
}


